package com.leyou.item.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.common.exception.LyException;
import com.leyou.item.dto.SpecGroupDTO;
import com.leyou.item.dto.SpecParamDTO;
import com.leyou.item.entity.SpecGroup;
import com.leyou.item.entity.SpecParam;
import com.leyou.item.mapper.SpecGroupMapper;
import com.leyou.item.service.SpecGroupService;
import com.leyou.item.service.SpecParamService;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class SpecGroupServiceImpl extends ServiceImpl<SpecGroupMapper, SpecGroup> implements SpecGroupService {
    private final SpecParamService paramService;

    public SpecGroupServiceImpl(SpecParamService paramService) {
        this.paramService = paramService;
    }

    //查询规格组及规格参数
    @Override
    public List<SpecGroupDTO> querySpecList(Long categoryId) {
        //查询规格组
        List<SpecGroupDTO> groupDTOList = SpecGroupDTO.convertEntityList(query().eq("category_id", categoryId).list());
        //健壮性判断
        if (CollectionUtils.isEmpty(groupDTOList)) {
            throw new LyException(404, "该分类下的规格组不存在");
        }
        //查询规格参数
        //循环根据groupId来查询group下的所有参数并且填充到groupDTOList中
        //循环内查询是不好的，需要查询很多次。需要优化
//        for (SpecGroupDTO groupDTO:groupDTOList){
//            Long groupId = groupDTO.getId();
//            List<SpecParamDTO> paramDTOList = paramService.querySpecParams(null, groupId, null);
//            groupDTO.setParams(paramDTOList);
//        }

        // 查询所有的规格参数
        List<SpecParamDTO> paramList = paramService.querySpecParams(categoryId,  null, null);
        // 对规格参数分组，groupId一致的按照流的方式分在一组
        //map的key是groupId，值是groupId一致的所有的param的集合
        Map<Long, List<SpecParamDTO>> map = paramList.stream()
                .collect(Collectors.groupingBy(SpecParamDTO::getGroupId));
        // 把参数放入group
        for (SpecGroupDTO groupDTO : groupDTOList) {
            groupDTO.setParams(map.get(groupDTO.getId()));
        }
        return groupDTOList;
    }

    //新增规格参数
    @Override
    public void insertSpecParam(SpecParamDTO paramDTO) {
        SpecParam specParam = paramDTO.toEntity(SpecParam.class);
        paramService.save(specParam);
    }
}